package 知识点复习.异步回调.异步任务的选择执行;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;

//随机选择(10+10)和(100+100)
public class ApplyToEitherDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                Integer firstStep = 10 + 10;
                System.out.println("firstStep out is " + firstStep);
                return firstStep;
            }
        });
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                Integer secondStep = 100 + 100;
                System.out.println("secondStep out is " + secondStep);
                return secondStep;
            }
        });
        //谁返回结果快，谁的结果将被第三步选择到
        CompletableFuture<Integer> future3 = future1.applyToEither(future2, new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer eitherOut) {
                return eitherOut;
            }
        });
        Integer result = future3.get();
        System.out.println("out is " + result);
    }
}
